# encoding: utf-8
"""
@Time   : 2018/12/21 12:00
@Author : XJH
"""

"""
4.3.3 实例14：演示get_variable和Variable的区别
Variable可以创建同样名字的变量，get_variable不行（报红）
"""
# import tensorflow as tf
#
# # 1. Variable用法
# var1 = tf.Variable(1.0, name="firstvar")
# print("var1:", var1.name)
# var1 = tf.Variable(2.0, name="firstvar")
# print("var1:", var1.name)
# var2 = tf.Variable(3.0)
# print("var2:", var2.name)
# var2 = tf.Variable(4.0)
# print("var2:", var2.name)
#
# with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     print("var1=", var1.eval())
#     print("var2=", var2.eval())
#
# # 2. get_Variable的用法
# get_var1 = tf.get_variable("firstvar", [1], initializer=tf.constant_initializer(0.3))
# print("get_var1:", get_var1.name)
# get_var1 = tf.get_variable("firstvar1", [1], initializer=tf.constant_initializer(0.4))
# print("get_var1:", get_var1.name)
#
# with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     print("get_var1=", get_var1.eval())

"""
4.3.4 实例15：在特定的作用域下获取变量
使用作用域可以让get_variable的变量名相同
"""
# import tensorflow as tf
# with tf.variable_scope("test1", ):
#     var1 = tf.get_variable("firstvar", shape=[2], dtype=tf.float32)
# with tf.variable_scope("test2", ):
#     var2 = tf.get_variable("firstvar", shape=[2], dtype=tf.float32)
# print("var1:", var1.name)
# print("var2:", var2.name)

"""
4.3.5 实例16：共享变量功能的实现
在变量作用域中使用reuse可以实现共享变量
"""
# import tensorflow as tf
# with tf.variable_scope("test1", ):
#     var1 = tf.get_variable("firstvar", shape=[2], dtype=tf.float32)
# with tf.variable_scope("test1", reuse=True):
#     var3 = tf.get_variable("firstvar", shape=[2], dtype=tf.float32)
# print("var1:", var1.name)
# print("var3", var3.name)

"""
4.3.6 实例17：初始化共享变量的作用域
在variable_scope中可以定义变量初始化的继承功能
"""
# import tensorflow as tf
#
# with tf.variable_scope("test1", initializer=tf.constant_initializer(0.4)):
#     var1 = tf.get_variable("firstvar", shape=[2,2], dtype=tf.float32)
#     with tf.variable_scope("test2"):
#         var2 = tf.get_variable("firstvar", shape=[2], dtype=tf.float32)
#         var3 = tf.get_variable("var3", shape=[2], initializer=tf.constant_initializer(0.3))
# with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     print("var1=", var1.eval())
#     print("var2=", var2.eval())
#     print("var3=", var3.eval())

"""
4.3.7 实例18：演示作用域和操作符的受限范围
当时用with variable_scope("name") as xxxscope的方式定义作用域时，所定义的作用域变量不受外围scope影响
"""
import tensorflow as tf

with tf.variable_scope("scope1") as sp:
    var1 = tf.get_variable("v", [1])

print("sp:", sp.name)
print("var1:", var1.name)

with tf.variable_scope("scope2"):
    var2 = tf.get_variable("v", [2])
    with tf.variable_scope(sp) as sp1:
        var3 = tf.get_variable("v3", [1])

print("sp1:", sp1.name)
print("var2:", var2.name)
print("var3:", var3.name)